home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / gdb / foo / remote-sa.m68k.shar / remcom.c
Encoding:
C/C++ Source or Header  |  1989-07-05  |  29.1 KB  |  874 lines

  1.  
  2. /****************************************************************************
  3.  
  4.         THIS SOFTWARE IS NOT COPYRIGHTED  
  5.    
  6.    HP offers the following for use in the public domain.  HP makes no
  7.    warranty with regard to the software or it's performance and the 
  8.    user accepts the software "AS IS" with all faults.
  9.  
  10.    HP DISCLAIMS ANY WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD
  11.    TO THIS SOFTWARE INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  12.    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  13.  
  14. ****************************************************************************/
  15.  
  16. /****************************************************************************
  17.  *  $Header: remcom.c,v 1.25 89/05/16 14:34:00 glenne Exp $                   
  18.  *
  19.  *  $Module name: remcom.c $  
  20.  *  $Revision: 1.25 $
  21.  *  $Date: 89/05/16 14:34:00 $
  22.  *  $Contributor:     Lake Stevens Instrument Division$
  23.  *  
  24.  *  $Description:     low level support for gdb debugger. $
  25.  *
  26.  *  $Considerations:  only works on target hardware $
  27.  *
  28.  *  $Written by:      Glenn Engel $
  29.  *  $ModuleState:     Experimental $ 
  30.  *
  31.  *  $NOTES:           See Below $
  32.  * 
  33.  *  To enable debugger support, two things need to happen.  One, a
  34.  *  call to set_debug_traps() is necessary in order to allow any breakpoints
  35.  *  or error conditions to be properly intercepted and reported to gdb.
  36.  *  Two, a breakpoint needs to be generated to begin communication.  This
  37.  *  is most easily accomplished by a call to breakpoint().  Breakpoint()
  38.  *  simulates a breakpoint by executing a trap #1.
  39.  *  
  40.  *  Some explanation is probably necessary to explain how exceptions are
  41.  *  handled.  When an exception is encountered the 68000 pushes the current
  42.  *  program counter and status register onto the supervisor stack and then
  43.  *  transfers execution to a location specified in it's vector table.
  44.  *  The handlers for the exception vectors are hardwired to jmp to an address
  45.  *  given by the relation:  (exception - 256) * 6.  These are decending 
  46.  *  addresses starting from -6, -12, -18, ...  By allowing 6 bytes for
  47.  *  each entry, a jsr, jmp, bsr, ... can be used to enter the exception 
  48.  *  handler.  Using a jsr to handle an exception has an added benefit of
  49.  *  allowing a single handler to service several exceptions and use the
  50.  *  return address as the key differentiation.  The vector number can be
  51.  *  computed from the return address by [ exception = (addr + 1530) / 6 ].
  52.  *  The sole purpose of the routine _catchException is to compute the
  53.  *  exception number and push it on the stack in place of the return address.
  54.  *  The external function exceptionHandler() is
  55.  *  used to attach a specific handler to a specific 68k exception.
  56.  *  For 68020 machines, the ability to have a return address around just
  57.  *  so the vector can be determined is not necessary because the '020 pushes an
  58.  *  extra word onto the stack containing the vector offset
  59.  * 
  60.  *  Because gdb will sometimes write to the stack area to execute function
  61.  *  calls, this program cannot rely on using the supervisor stack so it
  62.  *  uses it's own stack area reserved in the int array remcomStack.  
  63.  * 
  64.  *************
  65.  *
  66.  *    The following gdb commands are supported:
  67.  * 
  68.  * command          function                               Return value
  69.  * 
  70.  *    g             return the value of the CPU registers  hex data or ENN
  71.  *    G             set the value of the CPU registers     OK or ENN
  72.  * 
  73.  *    mAA..AA,LLLL  Read LLLL bytes at address AA..AA      hex data or ENN
  74.  *    MAA..AA,LLLL: Write LLLL bytes at address AA.AA      OK or ENN
  75.  * 
  76.  *    c             Resume at current address              SNN   ( signal NN)
  77.  *    cAA..AA       Continue at address AA..AA             SNN
  78.  * 
  79.  *    s             Step one instruction                   SNN
  80.  *    sAA..AA       Step one instruction from AA..AA       SNN
  81.  * 
  82.  *    k             kill
  83.  *
  84.  *    ?             What was the last sigval ?             SNN   (signal NN)
  85.  * 
  86.  * All commands and responses are sent with a packet which includes a 
  87.  * checksum.  A packet consists of 
  88.  * 
  89.  * $<packet info>#<checksum>.
  90.  * 
  91.  * where
  92.  * <packet info> :: <characters representing the command or response>
  93.  * <checksum>    :: < two hex digits computed as modulo 256 sum of <packetinfo>>
  94.  * 
  95.  * When a packet is received, it is first acknowledged with either '+' or '-'.
  96.  * '+' indicates a successful transfer.  '-' indicates a failed transfer.
  97.  * 
  98.  * Example:
  99.  * 
  100.  * Host:                  Reply:
  101.  * $m0,10#2a               +$00010203040506070809101112131415#42
  102.  * 
  103.  ****************************************************************************/
  104.  
  105. #include <stdio.h>
  106. #include <string.h>
  107. #include <setjmp.h>
  108.  
  109. /************************************************************************
  110.  *
  111.  * external low-level support routines 
  112.  */
  113. typedef void (*ExceptionHook)(int);   /* pointer to function with int parm */
  114. typedef void (*Function)();           /* pointer to a function */
  115.  
  116. extern putDebugChar();   /* write a single character      */
  117. extern getDebugChar();   /* read and return a single char */
  118.  
  119. extern Function exceptionHandler();  /* assign an exception handler */
  120. extern ExceptionHook exceptionHook;  /* hook variable for errors/exceptions */
  121.  
  122.  
  123. /************************************************************************/
  124. /* BUFMAX defines the maximum number of characters in inbound/outbound buffers*/
  125. /* at least NUMREGBYTES*2 are needed for register packets */
  126. #define BUFMAX 400
  127.  
  128. static char initialized;  /* boolean flag. != 0 means we've been initialized */
  129.  
  130. int     remote_debug = 0;
  131. /*  debug >  0 prints ill-formed commands in valid packets & checksum errors */ 
  132.  
  133. char hexchars[]="0123456789abcdef";
  134.  
  135. /* there are 180 bytes of registers on a 68020 w/68881      */
  136. /* many of the fpa registers are 12 byte (96 bit) registers */
  137. #define NUMREGBYTES 180
  138. enum regnames {D0,D1,D2,D3,D4,D5,D6,D7, 
  139.                A0,A1,A2,A3,A4,A5,A6,A7, 
  140.                PS,PC,
  141.                FP0,FP1,FP2,FP3,FP4,FP5,FP6,FP7,
  142.                FPCONTROL,FPSTATUS,FPIADDR
  143.               };
  144.  
  145. typedef struct FrameStruct
  146. {
  147.     struct FrameStruct  *previous;
  148.     int       exceptionPC;      /* pc value when this frame created */
  149.     int       exceptionVector;  /* cpu vector causing exception     */
  150.     short     frameSize;        /* size of cpu frame in words       */
  151.     short     sr;               /* for 68000, this not always sr    */
  152.     int       pc;
  153.     short     format;
  154.     int       fsaveHeader;
  155.     int       morejunk[0];        /* exception frame, fp save... */
  156. } Frame;
  157.  
  158. #define FRAMESIZE 500
  159. static Frame *lastFrame;
  160. static int   frameStack[FRAMESIZE];
  161.  
  162. /*
  163.  * these should not be static cuz they can be used outside this module
  164.  */
  165. int registers[NUMREGBYTES/4];
  166. int superStack;
  167.  
  168. static int remcomStack[400];
  169. static int* stackPtr = &remcomStack[399];
  170.  
  171. /*
  172.  * In many cases, the system will want to continue exception processing
  173.  * when a continue command is given.  
  174.  * oldExceptionHook is a function to invoke in this case.
  175.  */
  176.  
  177. static ExceptionHook oldExceptionHook;
  178.  
  179. /* the size of the exception stack on the 68020 varies with the type of
  180.  * exception.  The following table is the number of WORDS used
  181.  * for each exception format.
  182.  */
  183. static short exceptionSize[] = { 4,4,6,4,4,4,4,4,29,10,16,46,4,4,4,4 };
  184.  
  185. /************* jump buffer used for setjmp/longjmp **************************/
  186. jmp_buf env;
  187.  
  188. /***************************  ASSEMBLY CODE MACROS *************************/
  189. /*                                        */
  190.  
  191. #ifdef __HAVE_68881__
  192. /* do an fsave, then remember the address to begin a restore from */
  193. #define SAVE_FP_REGS()    asm(" fsave   a0@-");        \
  194.               asm(" fmovemx fp0-fp7,_registers+72");        \
  195.               asm(" fmoveml fpcr/fpsr/fpi,_registers+168"); 
  196. #define RESTORE_FP_REGS() asm(" fmoveml _registers+168,fpcr/fpsr/fpi"); \
  197.               asm(" fmovemx _registers+72,fp0-fp7");          \
  198.               asm(" frestore a0@+");
  199. #else
  200. #define SAVE_FP_REGS()
  201. #define RESTORE_FP_REGS()
  202. #endif /* __HAVE_68881__ */
  203.  
  204. asm("
  205. .text
  206. .globl _return_to_super
  207. _return_to_super:
  208.         movel   _registers+60,sp /* get new stack pointer */        
  209.         movel   _lastFrame,a0   /* get last frame info  */              
  210.         bra     return_to_any
  211.  
  212. .globl _return_to_user
  213. _return_to_user:
  214.         movel   _registers+60,a0 /* get usp */                          
  215.         movel   a0,usp           /* set usp */                
  216.         movel   _superStack,sp  /* get original stack pointer */        
  217.  
  218. return_to_any:
  219.         movel   _lastFrame,a0   /* get last frame info  */              
  220.         movel   a0@+,_lastFrame /* link in previous frame     */        
  221.         addql   #8,a0           /* skip over pc, vector#*/              
  222.         movew   a0@+,d0         /* get # of words in cpu frame */       
  223.         addw    d0,a0           /* point to end of data        */       
  224.         addw    d0,a0           /* point to end of data        */       
  225.         movel   a0,a1                                                   
  226. #                                                                       
  227. # copy the stack frame                                                  
  228.         subql   #1,d0                                                   
  229. copyUserLoop:                                                               
  230.         movew   a1@-,sp@-                                               
  231.         dbf     d0,copyUserLoop                                             
  232. ");                                                                     
  233.         RESTORE_FP_REGS()                                              
  234.    asm("   moveml  _registers,d0-d7/a0-a6");                    
  235.    asm("   rte");  /* pop and go! */                                    
  236.  
  237. #define DISABLE_INTERRUPTS()   asm("         oriw   #0x0700,sr");
  238. #define BREAKPOINT() asm("   trap #1");
  239.  
  240. /* this function is called immediately when a level 7 interrupt occurs */
  241. /* if the previous interrupt level was 7 then we're already servicing  */
  242. /* this interrupt and an rte is in order to return to the debugger.    */
  243. /* For the 68000, the offset for sr is 6 due to the jsr return address */
  244. asm("
  245. .text
  246. .globl __debug_level7
  247. __debug_level7:
  248.     movew   d0,sp@-");
  249. #ifdef mc68020
  250. asm("    movew   sp@(2),d0");
  251. #else
  252. asm("    movew   sp@(6),d0");
  253. #endif
  254. asm("    andiw   #0x700,d0
  255.     cmpiw   #0x700,d0
  256.     beq     _already7
  257.         movew   sp@+,d0    
  258.         bra     __catchException
  259. _already7:
  260.     movew   sp@+,d0");
  261. #ifndef mc68020
  262. asm("    lea     sp@(4),sp");     /* pull off 68000 return address */
  263. #endif
  264. asm("    rte");
  265.  
  266. extern void _catchException();
  267.  
  268. #ifdef mc68020
  269. /* This function is called when a 68020 exception occurs.  It saves
  270.  * all the cpu and fpcp regs in the _registers array, creates a frame on a
  271.  * linked list of frames which has the cpu and fpcp stack frames needed
  272.  * to properly restore the context of these processors, and invokes
  273.  * an exception handler (remcom_handler).
  274.  *
  275.  * stack on entry:                       stack on exit:
  276.  *   N bytes of junk                     exception # MSWord
  277.  *   Exception Format Word               exception # MSWord
  278.  *   Program counter LSWord              
  279.  *   Program counter MSWord             
  280.  *   Status Register                    
  281.  *                                       
  282.  *                                       
  283.  */
  284. asm(" 
  285. .text
  286. .globl __catchException
  287. __catchException:");
  288. DISABLE_INTERRUPTS();
  289. asm("
  290.         moveml  d0-d7/a0-a6,_registers /* save registers        */
  291.     movel    _lastFrame,a0    /* last frame pointer */
  292. ");
  293. SAVE_FP_REGS();        
  294. asm("
  295.     lea     _registers,a5   /* get address of registers     */
  296.         movew   sp@,d1          /* get status register          */
  297.         movew   d1,a5@(66)      /* save sr             */    
  298.     movel   sp@(2),a4       /* save pc in a4 for later use  */
  299.         movel   a4,a5@(68)      /* save pc in _regisers[]          */
  300.  
  301. #
  302. # figure out how many bytes in the stack frame
  303.     movew   sp@(6),d0    /* get '020 exception format    */
  304.         movew   d0,d2           /* make a copy of format word   */
  305.         andiw   #0xf000,d0      /* mask off format type         */
  306.         rolw    #5,d0           /* rotate into the low byte *2  */
  307.         lea     _exceptionSize,a1   
  308.         addw    d0,a1           /* index into the table         */
  309.     movew   a1@,d0          /* get number of words in frame */
  310.         movew   d0,d3           /* save it                      */
  311.         subw    d0,a0        /* adjust save pointer          */
  312.         subw    d0,a0        /* adjust save pointer(bytes)   */
  313.     movel   a0,a1           /* copy save pointer            */
  314.     subql   #1,d0           /* predecrement loop counter    */
  315. #
  316. # copy the frame
  317. saveFrameLoop:
  318.     movew      sp@+,a1@+
  319.     dbf     d0,saveFrameLoop
  320. #
  321. # now that the stack has been clenaed,
  322. # save the a7 in use at time of exception
  323.         movel   sp,_superStack  /* save supervisor sp           */
  324.         andiw   #0x2000,d1      /* were we in supervisor mode ? */
  325.         beq     userMode       
  326.         movel   a7,a5@(60)      /* save a7                  */
  327.         bra     a7saveDone
  328. userMode:  
  329.     movel   usp,a1        
  330.         movel   a1,a5@(60)      /* save user stack pointer    */
  331. a7saveDone:
  332.  
  333. #
  334. # save size of frame
  335.         movew   d3,a0@-
  336.  
  337. #
  338. # compute exception number
  339.     andl    #0xfff,d2       /* mask off vector offset    */
  340.     lsrw    #2,d2       /* divide by 4 to get vect num    */
  341.         movel   d2,a0@-         /* save it                      */
  342. #
  343. # save pc causing exception
  344.         movel   a4,a0@-
  345. #
  346. # save old frame link and set the new value
  347.     movel    _lastFrame,a1    /* last frame pointer */
  348.     movel   a1,a0@-        /* save pointer to prev frame    */
  349.         movel   a0,_lastFrame
  350.  
  351.         movel   d2,sp@-        /* push exception num           */
  352.     movel   _exceptionHook,a0  /* get address of handler */
  353.         jbsr    a0@             /* and call it */
  354.         jmp     __returnFromException     /* now, return        */
  355. ");
  356. #else /* mc68000 */
  357. /* This function is called when an exception occurs.  It translates the
  358.  * return address found on the stack into an exception vector # which
  359.  * is then handled by either handle_exception or a system handler.
  360.  * _catchException provides a front end for both.  
  361.  *
  362.  * stack on entry:                       stack on exit:
  363.  *   Program counter MSWord              exception # MSWord 
  364.  *   Program counter LSWord              exception # MSWord
  365.  *   Status Register                     
  366.  *   Return Address  MSWord              
  367.  *   Return Address  LSWord             
  368.  */
  369. asm("
  370. .text
  371. .globl __catchException
  372. __catchException:");
  373. DISABLE_INTERRUPTS();
  374. asm("
  375.         moveml d0-d7/a0-a6,_registers  /* save registers               */
  376.     movel    _lastFrame,a0    /* last frame pointer */
  377. ");
  378. SAVE_FP_REGS();        
  379. asm("
  380.         lea     _registers,a5   /* get address of registers     */
  381.         movel   sp@+,d2         /* pop return address           */
  382.     addl     #1530,d2        /* convert return addr to     */
  383.     divs     #6,d2       /*  exception number        */
  384.     extl    d2   
  385.  
  386.         moveql  #3,d3           /* assume a three word frame     */
  387.  
  388.         cmpiw   #3,d2           /* bus error or address error ? */
  389.         bgt     normal          /* if >3 then normal error      */
  390.         movel   sp@+,a0@-       /* copy error info to frame buff*/
  391.         movel   sp@+,a0@-       /* these are never used         */
  392.         moveql  #7,d3           /* this is a 7 word frame       */
  393.      
  394. normal:   
  395.     movew   sp@+,d1         /* pop status register          */
  396.         movel   sp@+,a4         /* pop program counter          */
  397.         movew   d1,a5@(66)      /* save sr             */    
  398.         movel   a4,a5@(68)      /* save pc in _regisers[]          */
  399.         movel   a4,a0@-         /* copy pc to frame buffer      */
  400.     movew   d1,a0@-         /* copy sr to frame buffer      */
  401.  
  402.         movel   sp,_superStack  /* save supervisor sp          */
  403.  
  404.         andiw   #0x2000,d1      /* were we in supervisor mode ? */
  405.         beq     userMode       
  406.         movel   a7,a5@(60)      /* save a7                  */
  407.         bra     saveDone             
  408. userMode:
  409.         movel   usp,a1        /* save user stack pointer     */
  410.         movel   a1,a5@(60)      /* save user stack pointer    */
  411. saveDone:
  412.  
  413.         movew   d3,a0@-         /* push frame size in words     */
  414.         movel   d2,a0@-         /* push vector number           */
  415.         movel   a4,a0@-         /* push exception pc            */
  416.  
  417. #
  418. # save old frame link and set the new value
  419.     movel    _lastFrame,a1    /* last frame pointer */
  420.     movel   a1,a0@-        /* save pointer to prev frame    */
  421.         movel   a0,_lastFrame
  422.  
  423.         movel   d2,sp@-        /* push exception num           */
  424.     movel   _exceptionHook,a0  /* get address of handler */
  425.         jbsr    a0@             /* and call it */
  426.         jmp     __returnFromException     /* now, return        */
  427. ");
  428. #endif
  429.  
  430.  
  431. /*
  432.  * remcomHandler is a front end for handle_exception.  It moves the
  433.  * stack pointer into an area reserved for debugger use in case the
  434.  * breakpoint happened in supervisor mode.
  435.  */
  436. asm("_remcomHandler:");
  437. asm("           addl    #4,sp");        /* pop off return address     */
  438. asm("           movel   sp@+,d0");      /* get the exception number   */
  439. asm("        movel   _stackPtr,sp"); /* move to remcom stack area  */
  440. asm("        movel   d0,sp@-");    /* push exception onto stack  */
  441. asm("        jbsr    _handle_exception");    /* this never returns */
  442. asm("           rts");                  /* return */
  443.  
  444. void _returnFromException( Frame *frame )
  445. {
  446.     /* if no existing frame, dummy one up */
  447.     if (! frame)
  448.     {
  449.         frame = lastFrame -1;
  450.         frame->frameSize = 4;
  451.         frame->format = 0;
  452.         frame->fsaveHeader = 0;
  453.         frame->previous = lastFrame;
  454.     }
  455.  
  456. #ifndef mc68020
  457.     /* a 68000 cannot use the internal info pushed onto a bus error
  458.      * or address error frame when doing an RTE so don't put this info
  459.      * onto the stack or the stack will creep every time this happens.
  460.      */
  461.     frame->frameSize=3;
  462. #endif
  463.  
  464.     /* throw away any frames in the list after this frame */
  465.     lastFrame = frame;
  466.  
  467.     frame->sr = registers[(int) PS];
  468.     frame->pc = registers[(int) PC];
  469.  
  470.     if (registers[(int) PS] & 0x2000)
  471.     { 
  472.         /* return to supervisor mode... */
  473.         return_to_super();
  474.     }
  475.     else
  476.     { /* return to user mode */
  477.         return_to_user();
  478.     }
  479. }
  480.  
  481. int hex(ch)
  482. char ch;
  483. {
  484.   if ((ch >= 'a') && (ch <= 'f')) return (ch-'a'+10);
  485.   if ((ch >= '0') && (ch <= '9')) return (ch-'0');
  486.   return (0);
  487. }
  488.  
  489.  
  490. /* scan for the sequence $<data>#<checksum>     */
  491. void getpacket(buffer)
  492. char * buffer;
  493. {
  494.   unsigned char checksum;
  495.   unsigned char xmitcsum;
  496.   int  i;
  497.   int  count;
  498.   char ch;
  499.   
  500.   do {
  501.     /* wait around for the start character, ignore all other characters */
  502.     while ((ch = getDebugChar()) != '$'); 
  503.     checksum = 0;
  504.     count = 0;
  505.     
  506.     /* now, read until a # or end of buffer is found */
  507.     while (count < BUFMAX) {
  508.       ch = getDebugChar();
  509.       if (ch == '#') break;
  510.       checksum = checksum + ch;
  511.       buffer[count] = ch;
  512.       count = count + 1;
  513.       }
  514.     buffer[count] = 0;
  515.  
  516.     if (ch == '#') {
  517.       xmitcsum = hex(getDebugChar()) << 4;
  518.       xmitcsum += hex(getDebugChar());
  519.       if ((remote_debug ) && (checksum != xmitcsum)) {
  520.         fprintf(stderr,"bad checksum.  My count = 0x%x, sent=0x%x. buf=%s\n",
  521.                              checksum,xmitcsum,buffer);
  522.       }
  523.       
  524.       if (checksum != xmitcsum) putDebugChar('-');  /* failed checksum */ 
  525.       else {
  526.      putDebugChar('+');  /* successful transfer */
  527.      /* if a sequence char is present, reply the sequence ID */
  528.      if (buffer[2] == ':') {
  529.         putDebugChar( buffer[0] );
  530.         putDebugChar( buffer[1] );
  531.         /* remove sequence chars from buffer */
  532.         count = strlen(buffer);
  533.         for (i=3; i <= count; i++) buffer[i-3] = buffer[i];
  534.      } 
  535.       } 
  536.     } 
  537.   } while (checksum != xmitcsum);
  538.   
  539. }
  540.  
  541. /* send the packet in buffer.  The host get's one chance to read it.  
  542.    This routine does not wait for a positive acknowledge.  */
  543.  
  544.  
  545. void putpacket(buffer)
  546. char * buffer;
  547. {
  548.   unsigned char checksum;
  549.   int  count;
  550.   char ch;
  551.   
  552.   /*  $<packet info>#<checksum>. */
  553.   do {
  554.   putDebugChar('$');
  555.   checksum = 0;
  556.   count    = 0;
  557.   
  558.   while (ch=buffer[count]) {
  559.     if (! putDebugChar(ch)) return;
  560.     checksum += ch;
  561.     count += 1;
  562.   }
  563.   
  564.   putDebugChar('#');
  565.   putDebugChar(hexchars[checksum >> 4]);
  566.   putDebugChar(hexchars[checksum % 16]);
  567.  
  568.   } while (1 == 0);  /* (getDebugChar() != '+'); */
  569.   
  570. }
  571.  
  572. static char  inbuffer[BUFMAX];
  573. static char  outbuffer[BUFMAX];
  574. static short error;
  575.  
  576.  
  577. void debug_error(format, parm)
  578. char * format;
  579. char * parm;
  580. {
  581.   if (remote_debug) fprintf(stderr,format,parm);
  582. }
  583.  
  584. /* convert the memory pointed to by mem into hex, placing result in buf */
  585. /* return a pointer to the last char put in buf (null) */
  586. char* mem2hex(mem, buf, count)
  587. char* mem;
  588. char* buf;
  589. int   count;
  590. {
  591.       int i;
  592.       unsigned char ch;
  593.       for (i=0;i<count;i++) {
  594.           ch = *mem++;
  595.           *buf++ = hexchars[ch >> 4];
  596.           *buf++ = hexchars[ch % 16];
  597.       }
  598.       *buf = 0; 
  599.       return(buf);
  600. }
  601.  
  602. /* convert the hex array pointed to by buf into binary to be placed in mem */
  603. /* return a pointer to the character AFTER the last byte written */
  604. char* hex2mem(buf, mem, count)
  605. char* buf;
  606. char* mem;
  607. int   count;
  608. {
  609.       int i;
  610.       unsigned char ch;
  611.       for (i=0;i<count;i++) {
  612.           ch = hex(*buf++) << 4;
  613.           ch = ch + hex(*buf++);
  614.           *mem++ = ch;
  615.       }
  616.       return(mem);
  617. }
  618.  
  619. /* a bus error has occurred, perform a longjmp
  620.    to return execution and allow handling of the error */
  621.  
  622. void handle_buserror()
  623. {
  624.   longjmp(env,1);
  625. }
  626.  
  627. /* this function takes the 68000 exception number and attempts to 
  628.    translate this number into a unix compatible signal value */
  629. int computeSignal( exceptionVector )
  630. int exceptionVector;
  631. {
  632.   int sigval;
  633.   switch (exceptionVector) {
  634.     case 2 : sigval = 10; break; /* bus error           */
  635.     case 3 : sigval = 10; break; /* address error       */
  636.     case 4 : sigval = 4;  break; /* illegal instruction */
  637.     case 5 : sigval = 8;  break; /* zero divide         */
  638.     case 6 : sigval = 16; break; /* chk instruction     */
  639.     case 7 : sigval = 16; break; /* trapv instruction   */
  640.     case 8 : sigval = 11; break; /* privilege violation */
  641.     case 9 : sigval = 5;  break; /* trace trap          */
  642.     case 10: sigval = 4;  break; /* line 1010 emulator  */
  643.     case 11: sigval = 4;  break; /* line 1111 emulator  */
  644.     case 31: sigval = 2;  break; /* interrupt           */
  645.     case 33: sigval = 5;  break; /* breakpoint          */
  646.     case 40: sigval = 8;  break; /* floating point err  */
  647.     case 48: sigval = 8;  break; /* floating point err  */
  648.     case 49: sigval = 8;  break; /* floating point err  */
  649.     case 50: sigval = 8;  break; /* zero divide         */
  650.     case 51: sigval = 8;  break; /* underflow           */
  651.     case 52: sigval = 8;  break; /* operand error       */
  652.     case 53: sigval = 8;  break; /* overflow            */
  653.     case 54: sigval = 8;  break; /* NAN                 */
  654.     default: 
  655.       sigval = 7;         /* "software generated"*/
  656.   }
  657.   return (sigval);
  658. }
  659.  
  660. /*
  661.  * This function does all command procesing for interfacing to gdb.
  662.  */
  663. void handle_exception(int exceptionVector)
  664. {
  665.   int    sigval;
  666.   int    addr, length;
  667.   char * ptr;
  668.   int    newPC;
  669.   Frame  *frame;
  670.   
  671.   if (remote_debug) printf("vector=%d, sr=0x%x, pc=0x%x\n", 
  672.                 exceptionVector,
  673.                 registers[ PS ], 
  674.                 registers[ PC ]);
  675.  
  676.   /* reply to host that an exception has occurred */
  677.   sigval = computeSignal( exceptionVector );
  678.   sprintf(outbuffer,"S%02x",sigval);
  679.   putpacket(outbuffer); 
  680.  
  681.   while (1==1) { 
  682.     error = 0;
  683.     outbuffer[0] = 0;
  684.     getpacket(inbuffer);
  685.     switch (inbuffer[0]) {
  686.       case '?' : sprintf(outbuffer,"S%02x",sigval);
  687.                  break; 
  688.       case 'd' : remote_debug = !(remote_debug);  /* toggle debug flag */
  689.                  break; 
  690.       case 'g' : /* return the value of the CPU registers */
  691.                 mem2hex((char*) registers, outbuffer, NUMREGBYTES);
  692.                 break;
  693.       case 'G' : /* set the value of the CPU registers - return OK */
  694.                 hex2mem(&inbuffer[1], (char*) registers, NUMREGBYTES);
  695.                 strcpy(outbuffer,"OK");
  696.                 break;
  697.       
  698.       /* mAA..AA,LLLL  Read LLLL bytes at address AA..AA */
  699.       case 'm' : 
  700.             if (setjmp(env) == 0) {
  701.             exceptionHandler(2,handle_buserror); 
  702.  
  703.             if (2 == sscanf(&inbuffer[1],"%x,%x",&addr,&length)) {
  704.               mem2hex((char*) addr, outbuffer, length);
  705.             }
  706.             else {
  707.               strcpy(outbuffer,"E01");
  708.               debug_error("malformed read memory command: %s",inbuffer);
  709.               }     
  710.                 } 
  711.         else {
  712.           exceptionHandler(2,_catchException);   
  713.           strcpy(outbuffer,"E03");
  714.           debug_error("bus error");
  715.           }     
  716.                 
  717.         /* restore handler for bus error */
  718.         exceptionHandler(2,_catchException);   
  719.         break;
  720.       
  721.       /* MAA..AA,LLLL: Write LLLL bytes at address AA.AA return OK */
  722.       case 'M' : 
  723.             if (setjmp(env) == 0) {
  724.             exceptionHandler(2,handle_buserror); 
  725.  
  726.             if (2 == sscanf(&inbuffer[1],"%x,%x:",&addr,&length)) {
  727.               ptr = strchr(inbuffer,':');
  728.               ptr += 1; /* point 1 past the colon */
  729.               hex2mem(ptr, (char*) addr, length);
  730.               strcpy(outbuffer,"OK");
  731.             }
  732.             else {
  733.               strcpy(outbuffer,"E02");
  734.               debug_error("malformed write memory command: %s",inbuffer);
  735.               }     
  736.                 } 
  737.         else {
  738.           exceptionHandler(2,_catchException);   
  739.           strcpy(outbuffer,"E03");
  740.           debug_error("bus error");
  741.           }     
  742.                 break;
  743.      
  744.      /* cAA..AA    Continue at address AA..AA(optional) */
  745.      /* sAA..AA   Step one instruction from AA..AA(optional) */
  746.      case 'c' : 
  747.      case 's' : 
  748.           /* try to read optional parameter, addr unchanged if no parm */
  749.           if (1 == sscanf(&inbuffer[1],"%x",®isters[ PC ])); 
  750.           newPC = registers[ PC];
  751.           
  752.           /* clear the trace bit */
  753.           registers[ PS ] &= 0x7fff;
  754.           
  755.           /* set the trace bit if we're stepping */
  756.           if (inbuffer[0] == 's') registers[ PS ] |= 0x8000;
  757.           
  758.           /*
  759.            * look for newPC in the linked list of exception frames.
  760.            * if it is found, use the old frame it.  otherwise,
  761.            * fake up a dummy frame in returnFromException().
  762.            */
  763.           if (remote_debug) printf("new pc = 0x%x\n",newPC);
  764.           frame = lastFrame;
  765.           while (frame)
  766.           {
  767.               if (remote_debug)
  768.                   printf("frame at 0x%x has pc=0x%x, except#=%d\n",
  769.                          frame,frame->exceptionPC,
  770.                          frame->exceptionVector);
  771.               if (frame->exceptionPC == newPC) break;  /* bingo! a match */
  772.               /*
  773.                * for a breakpoint instruction, the saved pc may
  774.                * be off by two due to re-executing the instruction
  775.                * replaced by the trap instruction.  Check for this.
  776.                */
  777.               if ((frame->exceptionVector == 33) &&
  778.                   (frame->exceptionPC == (newPC+2))) break;
  779.               frame = frame->previous;
  780.           }
  781.           
  782.           /*
  783.            * If we found a match for the PC AND we are not returning
  784.            * as a result of a breakpoint (33),
  785.            * trace exception (9), nmi (31), jmp to
  786.            * the old exception handler as if this code never ran.
  787.            */
  788.           if (frame) 
  789.           {
  790.               if ((frame->exceptionVector != 9)  && 
  791.                   (frame->exceptionVector != 31) && 
  792.                   (frame->exceptionVector != 33))
  793.               { 
  794.                   /*
  795.                    * invoke the previous handler.
  796.                    */
  797.                   if (oldExceptionHook)
  798.                       (*oldExceptionHook) (frame->exceptionVector);
  799.                   newPC = registers[ PC ];    /* pc may have changed  */
  800.                   if (newPC != frame->exceptionPC)
  801.                   {
  802.                       if (remote_debug)
  803.                           printf("frame at 0x%x has pc=0x%x, except#=%d\n",
  804.                                  frame,frame->exceptionPC,
  805.                                  frame->exceptionVector);
  806.                       /* dispose of this frame, we're skipping it (longjump?)*/
  807.                       lastFrame = frame->previous;
  808.                       frame = (Frame *) 0;
  809.                   }
  810.               }
  811.           }         
  812.  
  813.           _returnFromException( frame );
  814.  
  815.           break;
  816.           
  817.       /* kill the program */
  818.       case 'k' :  /* do nothing */
  819.                 break;
  820.       } /* switch */ 
  821.     
  822.     /* reply to the request */
  823.     putpacket(outbuffer); 
  824.     }
  825. }
  826.  
  827.  
  828. /* this function is used to set up exception handlers for tracing and 
  829.    breakpoints */
  830. void set_debug_traps()
  831. {
  832. extern void _debug_level7();
  833. extern void remcomHandler();
  834. int exception;
  835.  
  836.   for (exception = 2; exception <= 23; exception++)
  837.       exceptionHandler(exception,_catchException);   
  838.  
  839.   /* level 7 interrupt              */
  840.   exceptionHandler(31,_debug_level7);    
  841.   
  842.   /* breakpoint exception (trap #1) */
  843.   exceptionHandler(33,_catchException);
  844.   
  845.   /* floating point error (trap #8) */
  846.   exceptionHandler(40,_catchException);
  847.   
  848.   /* 48 to 54 are floating point coprocessor errors */
  849.   for (exception = 48; exception <= 54; exception++)
  850.       exceptionHandler(exception,_catchException);   
  851.  
  852.   if (oldExceptionHook != remcomHandler)
  853.   {
  854.       oldExceptionHook = exceptionHook;
  855.       exceptionHook    = remcomHandler;
  856.   }
  857.   
  858.   initialized = 1;
  859.  
  860.   lastFrame = (Frame *) &frameStack[FRAMESIZE-1];
  861.   lastFrame->previous = (Frame *) 0;
  862. }
  863.  
  864. /* This function will generate a breakpoint exception.  It is used at the
  865.    beginning of a program to sync up with a debugger and can be used
  866.    otherwise as a quick means to stop program execution and "break" into
  867.    the debugger. */
  868.    
  869. void breakpoint()
  870. {
  871.   if (initialized) BREAKPOINT();
  872. }
  873.  
  874.